import React, { useState, Suspense, useEffect } from 'react';
import { HashRouter as Router, Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import {
  Layout,
  Menu,
  Space,
  Typography,
  Modal,
  ConfigProvider,
  Avatar,
  Dropdown,
  MenuProps,
  Spin
} from 'antd';
import {
  CalculatorOutlined,
  BarChartOutlined,
  UserOutlined,
  LogoutOutlined,
  HomeOutlined,
  TeamOutlined,
  SettingOutlined
} from '@ant-design/icons';
import zhCN from 'antd/locale/zh_CN';
import { AuthProvider } from './contexts/AuthProvider';
import ProtectedRoute from './components/ProtectedRoute';
import { useAuth } from './contexts/AuthProvider';
import './App.css';

// 懒加载页面组件
const Login = React.lazy(() => import('./pages/Login'));
const Home = React.lazy(() => import('./pages/Home'));
const ProfitCalculator = React.lazy(() => import('./pages/ProfitCalculator'));
const FundInvestmentPlan = React.lazy(() => import('./pages/FundInvestmentPlan'));
const StockInvestmentPlan = React.lazy(() => import('./pages/StockInvestmentPlan'));
const Settings = React.lazy(() => import('./pages/Settings'));
const UserManagement = React.lazy(() => import('./pages/UserManagement'));

const { Header, Content, Footer, Sider } = Layout;
const { Text } = Typography;

// 加载组件
const LoadingComponent: React.FC = () => (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '200px' 
  }}>
    <Spin size="large" tip="页面加载中..." />
  </div>
);

interface MenuItem {
  key: string;
  icon: React.ReactNode;
  label: string;
  path: string;
}

const AppLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, profile, signOut } = useAuth();
  const [collapsed, setCollapsed] = useState<boolean>(false);
  const [activeMenu, setActiveMenu] = useState<string>('1');

  console.info("user=>", user)
  console.info("profile=>", profile)

  // 基础菜单项
  const baseMenuItems: MenuItem[] = [
    {
      key: '1',
      icon: <HomeOutlined />,
      label: '首页概览',
      path: '/'
    },
    {
      key: '2',
      icon: <BarChartOutlined />,
      label: '盈利情况计算',
      path: '/profit-calculator'
    },
    {
      key: '3',
      icon: <CalculatorOutlined />,
      label: '公募基金投资计划',
      path: '/fund-plan'
    },
    {
      key: '4',
      icon: <CalculatorOutlined />,
      label: '证券投资计划',
      path: '/stock-plan'
    },
    {
      key: '5',
      icon: <SettingOutlined />,
      label: '系统设置',
      path: '/settings'
    }
  ];

  // 超级管理员专用菜单项
  const adminMenuItems: MenuItem[] = [
    {
      key: '6',
      icon: <TeamOutlined />,
      label: '用户管理',
      path: '/user-management'
    }
  ];

  // 根据用户角色动态生成菜单
  const menuItems = profile?.role === 'superadmin'
    ? [...baseMenuItems, ...adminMenuItems]
    : baseMenuItems;

  // 根据当前路径获取对应的菜单key
  const getActiveMenuKey = (pathname: string): string => {
    const item = menuItems.find(item => item.path === pathname);
    return item ? item.key : '1'; // 默认返回首页
  };

  // 监听路由变化，更新菜单激活状态
  useEffect(() => {
    const currentKey = getActiveMenuKey(location.pathname);
    setActiveMenu(currentKey);
  }, [location.pathname, menuItems]);

  const handleMenuClick = ({ key }: { key: string }) => {
    setActiveMenu(key);
    const item = menuItems.find(item => item.key === key);
    if (item) {
      navigate(item.path);
    }
  };

  // 用户菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人信息',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '系统设置',
      onClick: () => {
        navigate('/settings');
        setActiveMenu('5'); // 手动设置菜单激活状态
      }
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: () => {
        Modal.confirm({
          title: '确认退出',
          content: '确定要退出登录吗？',
          onOk: async () => {
            try {
              await signOut();
              navigate('/login');
            } catch (error) {
              console.error('退出登录失败:', error);
              navigate('/login'); // 即使失败也跳转到登录页
            }
          }
        });
      }
    }
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        width={250}
        style={{
          overflow: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0,
          top: 0,
          bottom: 0,
        }}
      >
        <div className="logo" style={{
          height: '64px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'white',
          fontSize: '18px',
          fontWeight: 'bold'
        }}>
          {collapsed ? 'AIA' : '理财投资助手'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[activeMenu]}
          onClick={handleMenuClick}
        >
          {menuItems.map(item => (
            <Menu.Item key={item.key} icon={item.icon}>
              {item.label}
            </Menu.Item>
          ))}
        </Menu>
      </Sider>

      <Layout
        className="site-layout"
        style={{
          marginLeft: collapsed ? 80 : 250,
          transition: 'margin-left 0.2s'
        }}
      >
        <Header className="header" style={{
          padding: 0,
          background: '#fff',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingRight: '24px'
        }}>
          <div></div>
          <Space>
            <Dropdown
              menu={{ items: userMenuItems }}
              placement="bottomRight"
              arrow
            >
              <Space style={{ cursor: 'pointer' }}>
                <Avatar size="small" icon={<UserOutlined />} />
                <span>{user?.profile?.name || user?.email}</span>
              </Space>
            </Dropdown>
          </Space>
        </Header>

        <Content style={{ margin: '24px 16px 0', overflow: 'initial' }}>
          <div className="content" style={{
            padding: 24,
            background: '#fff',
            minHeight: 'calc(100vh - 160px)',
            borderRadius: '8px'
          }}>
            <Suspense fallback={<LoadingComponent />}>
              <Routes>
                <Route path="/" element={
                  <ProtectedRoute>
                    <Home />
                  </ProtectedRoute>
                } />
                <Route path="/profit-calculator" element={
                  <ProtectedRoute>
                    <ProfitCalculator />
                  </ProtectedRoute>
                } />
                <Route path="/fund-plan" element={
                  <ProtectedRoute>
                    <FundInvestmentPlan />
                  </ProtectedRoute>
                } />
                <Route path="/stock-plan" element={
                  <ProtectedRoute>
                    <StockInvestmentPlan />
                  </ProtectedRoute>
                } />
                <Route path="/settings" element={
                  <ProtectedRoute>
                    <Settings />
                  </ProtectedRoute>
                } />
                <Route path="/user-management" element={
                  <ProtectedRoute>
                    <UserManagement />
                  </ProtectedRoute>
                } />
              </Routes>
            </Suspense>
          </div>
        </Content>

        <Footer style={{ textAlign: 'center' }}>
          <Text type="secondary">理财投资工具助手 v1.0.0 ©2025 Created by Wang yanan</Text>
        </Footer>
      </Layout>
    </Layout>
  );
};

const App: React.FC = () => {
  return (
    <Router>
      <ConfigProvider
        theme={{
          token: {
            colorPrimary: '#1890ff',
          },
        }}
        locale={zhCN}
      >
        <AuthProvider>
          <Suspense fallback={<LoadingComponent />}>
            <Routes>
              <Route path="/login" element={<Login />} />
              <Route path="/*" element={<AppLayout />} />
            </Routes>
          </Suspense>
        </AuthProvider>
      </ConfigProvider>
    </Router>
  );
};

export default App;